﻿using System;
using System.IO;

namespace WikiMaml
{
    public class Translator
    {
        private readonly IRenderingEngine renderingEngine;
        private readonly IFileService fileService;
        private readonly ILogger logger;

        public Translator(IRenderingEngine renderingEngine, IFileService fileService, ILogger logger)
        {
            this.renderingEngine = renderingEngine;
            this.fileService = fileService;
            this.logger = logger;
        }

        public bool Translate(string[] inputFiles, string rootDir, string outputDir)
        {
            bool allTranslated = true;

            foreach (string file in inputFiles)
            {
                string fileName = Path.GetFileNameWithoutExtension(file) + ".aml";
                string recursiveDir = Path.GetDirectoryName(file).Replace(rootDir, string.Empty);
                if (recursiveDir.StartsWith("\\"))
                    recursiveDir = recursiveDir.Substring(1);
                string recursiveFilePath = Path.Combine(recursiveDir, fileName);

                try
                {
                    string[] pathParts = recursiveDir.Split(new[] { '\\' }, StringSplitOptions.RemoveEmptyEntries);
                    string newFilePath = Path.Combine(outputDir, recursiveFilePath);

                    string directory = outputDir;
                    foreach (string part in pathParts)
                    {
                        directory = Path.Combine(directory, part);
                        fileService.EnsureDirectoryExists(directory);
                    }

                    string wikiContent = fileService.ReadAllText(file);
                    fileService.WriteAllText(newFilePath, renderingEngine.Render(wikiContent));
                    logger.LogMessage("Created Documentation '{0}'", recursiveFilePath);
                }
                catch (Exception ex)
                {
                    logger.LogError("Error Creating Documentation for '{0}': {1}", recursiveFilePath, ex.Message);
                    allTranslated = false;
                }
            }

            return allTranslated;
        }
    }
}
